package util;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;

/**
 * The Periodic class provides access to the periodic table via the included xml data.
 */
public class Periodic {

    /**
     * This hashmap contains the periodic table with the keys being atomic symbols.
     */
    public static HashMap<String, Atom> elements;

    /**
     * This method initializes of the global variables which we will be using by reading in a xml file.
     * In the future, there will be polyatomic ions
     */
    public static void initialize() {
        try {
            elements = new HashMap<String, Atom>();

            BufferedInputStream file;
            try {
                file = new BufferedInputStream(new FileInputStream(new File("trunk//util//periodic_table.xml")));
            } catch (Exception e) {
                file = new BufferedInputStream(new FileInputStream(new File("src//util//periodic_table.xml")));
            }
            //Both project setups should work now.
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = db.parse(file);
            NodeList nodeLst = doc.getElementsByTagName("ATOM");
            getElements(nodeLst);
        } catch (Exception e) {
            e.printStackTrace();
            //Terminate to avoid the memory leak that seems to occur if file is not found...
            System.exit(1);
        }

    }

    /**
     * Puts each element into a hash map, with their symbols as the key
     *
     * @param nodeLst The list of nodes from= the xml file.
     */
    private static void getElements(NodeList nodeLst) {
        Node fstNode;
        for (int s = 0; s < nodeLst.getLength(); s++) {
            fstNode = nodeLst.item(s);
            if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                Atom k = new Atom(fstNode);
                elements.put(k.getSymbol(), k);
            }
        }
    }
}
